var gulp = require('gulp');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var cleanCss = require('gulp-clean-css');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var ngAnnotate = require('gulp-ng-annotate');
var concat = require('gulp-concat');
var notify = require("gulp-notify");
var templateCache = require('gulp-angular-templatecache');
var htmlmin = require('gulp-htmlmin');
var autoprefix = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var minimist = require('minimist');
var replace = require('gulp-replace');

var knownOptions = {
    string: 'env',
    default: {env: process.env.NODE_ENV || 'prd', lang: 'zh_CN'}
};
var options = minimist(process.argv.slice(2), knownOptions);

// 源代码目录
var src_paths_servicecenter = {
    sass: ['src/servicecenter/scss/*.scss'],
    css: ['src/servicecenter/css/*.css'],
    js: ['src/servicecenter/**/*.js', '!src/servicecenter/test/*.js'],
    html: ['src/servicecenter/views/*.html'],
    index: ['src/servicecenter/index.html']
};

// 中间目录（sass实时编译为css，html模板实时编译为template）
var dest_paths_servicecenter = {
    css: 'src/servicecenter/css/',
    html: 'src/servicecenter/'
};

// 发布目录（build打包结果）
var dist_paths_servicecenter = 'dist/' + options.lang + '/servicecenter/';

gulp.task('servicecenter-watch', false, function () {
    gulp.watch(src_paths_servicecenter.sass, ['servicecenter-sass']);
    gulp.watch(src_paths_servicecenter.html, ['servicecenter-template-cache']);
});

gulp.task('servicecenter-sass', false, function (done) {
    gulp.src(src_paths_servicecenter.sass)
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(autoprefix({ browsers: ['last 2 versions'] }))
        .pipe(gulp.dest(dest_paths_servicecenter.css))
        .on('end', done);
});

gulp.task('servicecenter-template-cache', false, function (done) {
    gulp.src(src_paths_servicecenter.html)
        .pipe(templateCache({module: 'service-center'}))
        .pipe(gulp.dest(dest_paths_servicecenter.html))
        .on('end', done);
});

gulp.task('build-servicecenter', '服务配置中心模块编译任务', ['servicecenter-template-cache'], function(done) {
    gulp.src(src_paths_servicecenter.index)
        .pipe(gulpif(options.lang === 'en_US', replace(/zh-CN/g, 'en-US')))
        .pipe(useref())
        .pipe(sourcemaps.init())
        .pipe(gulpif('*.js', ngAnnotate({
            single_quotes: true
        })))
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.css', cleanCss()))
        //.pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulpif('*.js', sourcemaps.write('./', {
            sourceRoot: './'
        })))
        .pipe(gulp.dest(dist_paths_servicecenter))
        .on('end', done);
});

gulp.task('task-servicecenter', '服务配置中心模块监听任务', ['servicecenter-watch'], function () {

});
